package com.lagou.edu.ssssession.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //有一些页面是不需要拦截的，例如登录页面
        HttpSession session = request.getSession();
        System.out.println("请求的路径为："+request.getRequestURI()+"    sessionId为："+session.getId());
        String loginStr = (String) session.getAttribute("login");
        if(loginStr!=null) {
            return true;
        }
        String redirect=request.getContextPath()+"/login";
        response.sendRedirect(redirect);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
